package com.heima.article.controller;

import com.heima.article.entity.ApArticle;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.repository.ApArticleSearchRepository;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("test")
@Api(tags = "APP已发布文章测试接口")
public class TestController {
    @Autowired
    private IApArticleService apArticleService;
    @Autowired
    private ApArticleSearchRepository searchRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 创建es完成
     * @return
     */
    @GetMapping("/createIndex")
    public ResponseResult createIndex(){
        boolean index = elasticsearchRestTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult("索引创建完成");
    }

    /**
     * 添加映射
     * @return
     */
    @GetMapping("/putMapping")
    public ResponseResult putMapping(){
        boolean mapping = elasticsearchRestTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult("映射创建完成");
    }

    /**
     * 保存文章列表
     * @return
     */
    @GetMapping("/addDoc")
    public ResponseResult addDoc(){
        List<ApArticle> articles = apArticleService.list();
        for (ApArticle article : articles) {
            ApArticleSearch apArticleSearch=new ApArticleSearch();
            BeanUtils.copyProperties(article,apArticleSearch);
            //保存到es中
            IndexQuery indexQuery=new IndexQuery();
            indexQuery.setId(apArticleSearch.getId().toString());
            indexQuery.setObject(apArticleSearch);
            elasticsearchRestTemplate.index(indexQuery);
        }
        return ResponseResult.okResult("导入es中完成");
    }

    @GetMapping("/del")
    public ResponseResult deleteAll(){
        searchRepository.deleteAll();
        return ResponseResult.okResult();
    }

    @GetMapping("/add")
    public ResponseResult addAll(){
        List<ApArticle> list = apArticleService.list();
        List<ApArticleSearch> searches=new ArrayList<>();
        for (ApArticle apArticle : list) {
            ApArticleSearch apArticleSearch=new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);
            searches.add(apArticleSearch);
        }
        searchRepository.saveAll(searches);
        return ResponseResult.okResult();
    }
}
